/**
 * 工具文件
 */
import httpClient from "./httpClient";
import APIPath from "./APIPath";
import storage from "./storage";
import * as config from './config'
// #ifdef H5
import { EventSourcePolyfill } from "event-source-polyfill";
import {CHANNEL_ID} from "./config";
// #endif


export default {
	_toast(param) {
		uni.showToast({
			...param
		})
	},
	toast(title, fn) {
		this._toast({
			title,
			duration: 2000,
			icon: 'none'
		})
		if(fn && typeof fn === 'function') {
			setTimeout(v => {
				fn()
			}, 1800)
		}
	},
	successToast(title) {
		this._toast({
			title,
			duration: 2000,
			icon: 'success'
		})
	},
	loadingToast(title) {
		this._toast({
			title,
			duration: 2000,
			icon: 'loading'
		})
	},
	showLoading(title = '加载中...') {
		uni.showLoading({
			title,
			mask: true
		})
	},
	ab2str(buf) {
		const decoder = new TextDecoder('utf-8');
		return decoder.decode(buf);
	},
	getStatusBarHeight() {
		try {
			const res = uni.getSystemInfoSync();
			return res.statusBarHeight;
		} catch (e) {
			// error
		}
	},
	hideLoading() {
		uni.hideLoading()
	},
	debugFn(devFn, fn) {
		if (process.env.NODE_ENV === 'development') {
			typeof devFn === 'function' && devFn()
		} else {
			typeof fn === 'function' && fn()
		}
	},
	checkPhone(phone) {
		return /^1\d{10}$/.test(phone)
	},
	checkSmsCode(phone) {
		return /^\d{6}$/.test(phone)
	},
	checkIdNo(no) {
		return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(no)
	},
	checkPwd(pwd) {
		return /^[\da-zA-Z~!@#$%^&*]{8,12}$/.test(pwd)
	},
	checkPrice(price) {
		return /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(price)
	},
	checkNumber(num) {
		return /^[1-9]\d*$/.test(num)
	},
	cloneObject(obj) {
		return JSON.parse(JSON.stringify(obj))
	},

    /**
     * 获取之前页面信息
     * @param len 之前几页，默认1
     * @returns {*}
     */
    getPrevPage(len = 1){
        const p = getCurrentPages()
        return p.length > len ? p[p.length - (1 + len)].$vm : null
    },

	gotoPage(path, isLogin = false) {
		const pathObj = [
			"/pages/index/index",
			"/pages/creation/index",
			"/pages/role/index",
			"/pages/draw/index",
			"/pages/my/index",
		]

		if (!path) {
			this.toast('敬请期待');
			return
		}

		if(isLogin) {
			const token = storage.getToken()
			if(!token) {
				this.gotoPage('/pages/login/userLogin')
			}
		}

		uni[pathObj.indexOf(path) > -1 ? 'switchTab' : 'navigateTo']({
			url: path
		})
	},
	switchTab(path) {
		uni.switchTab({
			url: path
		})
	},
	redirectToPage(path) {
		uni.redirectTo({
			url: path
		})
	},
	replacePage(path) {
		uni.reLaunch({
			url: path
		})
	},
	navigateBack() {
		uni.navigateBack()
	},
	back() {
		uni.navigateBack()
	},
	random(min, max) {
		return Math.floor(Math.random() * (max - min)) + min;
	},
	getTimeVal(val) {
		if (!val) return ''
		val = typeof val === 'string' && val.indexOf('-') > -1 ? val.replace(/-/g, "/") : val
		return val
	},
	formatDate(val, fmt = 'yyyy-MM-dd hh:mm:ss', isEnd = false, isInit = true) {
		if (!val) return ''
		val = this.getTimeVal(parseInt(val))
		var timezone = 8
		var offset_GMT = new Date(val).getTimezoneOffset()
		var nowDate = new Date(val).getTime()
		val = new Date(nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000);
		const date = new Date(isInit ? val * (isEnd ? 1000 : 1) : val);
		let o = {
			"M+": date.getMonth() + 1,
			"d+": date.getDate(),
			"h+": date.getHours(),
			"m+": date.getMinutes(),
			"s+": date.getSeconds(),
			"q+": Math.floor((date.getMonth() + 3) / 3),
			"S": date.getMilliseconds()
		}
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))

		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
				"00" + o[k]).substr(("" + o[k]).length)))

		return fmt;
	},

    downloadImage(url) {
        return new Promise((resolve, reject) => {
            uni.downloadFile({
                url: url,
                success: (res) => {
                    return resolve(res)
                },
                fail: (err) => {
                    return reject(err)
                }
            })
        })
    },

	callPhone(phone) {
		if(!phone)return;
		uni.makePhoneCall({
			phoneNumber: phone
		});
	},

	getDateToInt(time) {
		if(!time) return ''
		return +new Date(time.replaceAll('-', '/'))
	},
	getDateToIsoInt(time) {
		if(!time) return ''
		return +new Date(time)
	},
	keepTwoDecimalFull(num) {
		var result = parseFloat(num);
		if (isNaN(result)) {
			return num;
		}
		result = Math.round(num * 100) / 100;
		var s_x = result.toString(); //将数字转换为字符串

		var pos_decimal = s_x.indexOf('.'); //小数点的索引值


		// 当整数时，pos_decimal=-1 自动补0
		if (pos_decimal < 0) {
			pos_decimal = s_x.length;
			s_x += '.';
		}

		// 当数字的长度< 小数点索引+2时，补0
		while (s_x.length <= pos_decimal + 2) {
			s_x += '0';
		}
		return s_x;
	},

	priceFormat(v) {
		return v > 0 ? (v / 100).toFixed(2) : '0.00'
	},
	distanceFilter(v) {
		if(v < 500) {
			return '500m内'
		}else if(v < 999) {
			return '1km内'
		}else if(v < 20000){
			return parseInt(v / 1000) + 'km内'
		}else{
			return parseInt(v / 1000) + 'km'
		}
	},
	distanceAFilter(v) {
		if(v < 500) {
			return '500m内'
		}else{
			return parseInt(v / 1000) + 'km内'
		}
	},
	getDateDiff(dateTimeStamp) {
		var timestamp = new Date(this.getDateToInt(dateTimeStamp)).getTime();
		var minute = 1000 * 60;
		var hour = minute * 60;
		var day = hour * 24;
		var halfamonth = day * 15;
		var month = day * 30;
		var year = day * 365;
		var now = new Date().getTime();
		var diffValue = now - timestamp;
		var result;
		if (diffValue < 0) {
			return;
		}
		var yearC = diffValue / year;
		var monthC = diffValue / month;
		var weekC = diffValue / (7 * day);
		var dayC = diffValue / day;
		var hourC = diffValue / hour;
		var minC = diffValue / minute;
		if (yearC >= 1) {
			result = "" + parseInt(yearC) + "年前";
		} else if (monthC >= 1) {
			result = "" + parseInt(monthC) + "月前";
		} else if (weekC >= 1) {
			result = "" + parseInt(weekC) + "周前";
		} else if (dayC >= 1) {
			result = "" + parseInt(dayC) + "天前";
		} else if (hourC >= 1) {
			result = "" + parseInt(hourC) + "小时前";
		} else if (minC >= 1) {
			result = "" + parseInt(minC) + "分钟前";
		} else
			result = "刚刚";
		return result;
	},

	lineUpCheck(id) {
		return new Promise((resolve, reject) => {
			wx.getFuzzyLocation({
				success: (res) => {
					httpClient.post({
						url: APIPath.projectLineUp.getDistance,
						data: {
							id,
							...res
						}
					}).then(res => {
						resolve()
					})
				},
				fail: (err) => {
					this.toast('地理位置获取失败，无法预约')
				}
			})
		})
	},
	showPrice(v) {
		if(!v) return 0;
		return v / 100
	},
	isWxWeb() {
		// #ifdef MP-WEIXIN
		return false;
		// #endif
		// #ifdef H5
		try{
			return navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger"
		}catch (e) {
			return false
		}
		// #endif
	},
	copy(str) {
		// 复制文本到剪切板
		uni.setClipboardData({
			data: str,
			success: () => {
				this.toast('复制成功')
			}
		})
	},
	getUrlWxMpCode() { // 截取url中的code方法
		var url = location.search
		this.winUrl = url
		var theRequest = new Object()
		if (url.indexOf("?") != -1) {
			var str = url.substr(1)
			var strs = str.split("&")
			for(var i = 0; i < strs.length; i ++) {
				theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1])
			}
		}
		console.log(theRequest)
		return theRequest ? theRequest.code : ''
	},
	// 判断是否为微信浏览器
	isWeixinBrowser() {
		let ua = navigator.userAgent.toLowerCase();
		return /micromessenger/.test(ua) ? true : false;
	},
	checkSseData(str) {
		return new Promise((resolve, reject) => {
			const data = typeof str === 'string' ? JSON.parse(str) : str
			if(data.code === 200) {
				resolve(data)
			}else{
				this.toast(data.msg || "异常")
			}
		})
	},
	 getUrlParam(name) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		var r = window.location.search.substr(1).match(reg);
		if (r != null) {
			return unescape(r[2]);
		}
		return null;
	},
	getSsm(onmessage, onError) {
		// #ifdef MP-WEIXIN
		const requestTask= uni.request({
			url: config.SSM_URL + APIPath.chat.createSse,
			data:{},
			method:'GET',
			responseType:'text',
			enableChunked:true,
			success:response=>{}})

		requestTask.onHeadersReceived(resheader=>{
			console.log(resheader)
		})
		requestTask.onChunkReceived(res => {
			const d = this.ab2str(res.data)
			let str = ''
			try{
				JSON.parse(d)
				str = d
			}catch (e) {
				str = '{' + d.slice(0, d.lastIndexOf("}")) + "}}"
				str = str.replace('data:', '"data":')
			}

			const s = JSON.parse(str)
			onmessage(s)
		})


		// #endif
		// #ifdef H5
		var eventSource = new EventSourcePolyfill(config.SSM_URL + APIPath.chat.createSse, {
			headers: {
				token: storage.getToken()
			}
		})
		eventSource.onopen = (event) => {
			console.log(event)
			console.log("开始输出后端返回值");
		};
		eventSource.onmessage = (event) => {
			onmessage(event)
		};
		eventSource.onerror = (event) => {
			onError(event)

		};

		// #endif
	},

	gotoLogin() {
		const config = storage.getConfig()
		if(config.loginType === 1){
			this.gotoPage('/pages/login/userLogin')
		}else{
			this.gotoPage('/pages/login/phonePasswordLogin')
		}
	},

	downloadImg(imgsrc) {
		// #ifdef MP-WEIXIN
		uni.downloadFile({
		  url: imgsrc,
		  success: (res) => {
		    if (res.statusCode === 200) {
		      uni.saveImageToPhotosAlbum({
		        filePath: res.tempFilePath,
		        success: (res) => {
		          this.toast('下载成功')
		        },
		        fail: (res) => {
		          this.toast('下载失败')
		        },
		      });
		    }else{
		      this.toast('下载失败')
		    }
		  }
		});
		// #endif
		// #ifdef H5
		if(config.CHANNEL_ID === 3) {
			return this.toast('请长按图片保存')
		}

		let num = imgsrc.lastIndexOf('/')+1
		let filename = imgsrc.substring(num)
		let [name, type] = filename.split('.')
		let image = new Image();
		// 解决跨域 Canvas 污染问题
		image.setAttribute("crossOrigin", "anonymous");
		image.onload = function () {
			let canvas = document.createElement("canvas");
			canvas.width = image.width;
			canvas.height = image.height;
			let context = canvas.getContext("2d");
			context.drawImage(image, 0, 0, image.width, image.height);
			let url = canvas.toDataURL(`image/${type}`); //得到图片的base64编码数据
			let a = document.createElement("a"); // 生成一个a元素
			let event = new MouseEvent("click"); // 创建一个单击事件
			a.download = name || "pic"; // 设置图片名称
			a.href = url; // 将生成的URL设置为a.href属性
			a.dispatchEvent(event); // 触发a的单击事件
			this.toast('下载成功')
		}
		//将资源链接赋值过去，才能触发image.onload 事件
		image.src = imgsrc
		// #endif
	}

}
